<template>
  <div class="wrap">
    <!-- header头部 -->
    <!-- <m-header
      :activeIndex="2"
      :backcolor="'#1968FA'"
      :color="'#fff'"
      opacity="1"
      hocolor="#fff"
      filter="blur(0px)"
      :islogin="false"
    ></m-header> -->
    <div style="height: 50px"></div>

    <!-- <div class="time-down">
      <div>
        {{ countDown }}
      </div>
    </div> -->
    <div class="container" style="width: 100%; max-width: 1200px">
      <el-page-header
        :title="'退出'"
        @back="goBack"
        :content="zuotiList.templateName"
      >
      </el-page-header>
      <div class="subject">
        <el-row :gutter="20">
          <el-col :sm="15">
            <div class="left-content">
              <p
                style="
                  background: #eaf1ff;
                  padding: 20px 30px;
                  font-size: 16px;
                  color: #333333;
                  font-weight: bold;
                "
              >
                {{ sujectType }}
              </p>
              <div ref="scrollMenuRef" class="scrollMenuBox">
                <div class="subbox-box">
                  <div>
                    <span class="tihao">{{ questionNumcopy + 1 }}</span>
                    <span style="margin-left: 10px">{{
                      timuList.topicContent
                    }}</span>
                  </div>
                  <div class="subbox" v-if="sujectType != '多选题'">
                    <div
                      class="options"
                      v-for="(item, index) in this.timuList.options"
                      :key="index"
                      @click="handleOptionTrue(item)"
                    >
                      <div
                        :class="`${
                          isOptuionSelcet == timuListCopy.options[index] ||
                          isOptuionSelcet == item
                            ? 'option is-option-select'
                            : 'option'
                        }`"
                      >
                        {{ item.split("、")[0] }}
                      </div>
                      <div>{{ splitFirst(item, "、")[1] }}</div>
                    </div>
                  </div>
                  <!-- 多选框 -->
                  <div class="subbox" v-else>
                    <el-checkbox-group
                      class="check-options"
                      v-model="checkList"
                    >
                      <el-checkbox
                        @change="(value) => handleCheckedChange(value, item)"
                        style="margin-bottom: 20px"
                        v-for="(item, index) in this.timuList.options"
                        :label="item.split('、')[0]"
                        :key="index"
                        >{{ item }}</el-checkbox
                      >
                    </el-checkbox-group>
                    <!-- <div
                      class="options"
                      v-for="(item, index) in this.timuList.options"
                      :key="index"
                      @click="handleOptionTrue(item)"
                    >
                      <div
                        :class="`${
                          isOptuionSelcet == timuListCopy.options[index] ||
                          isOptuionSelcet == item
                            ? 'check-option is-checkbox-select'
                            : 'check-option'
                        }`"
                      >
                        {{ item.split("、")[0] }}
                      </div>
                      <div>{{ item.split("、")[1] }}</div>
                    </div> -->
                  </div>
                </div>
              </div>
            </div>
            <div class="nextlast-box">
              <div class="btn-box">
                <el-button class="last-btn" @click="handleNextQuestion('last')"
                  >上一题</el-button
                >
                <el-button class="next-btn" @click="handleNextQuestion('next')"
                  >下一题</el-button
                >
              </div>
            </div>
            <div class="submit">
              <el-button type="primary" @click="handleIsSubmit(true, 1)"
                >交 卷</el-button
              >
            </div>
          </el-col>
          <!-- 答题卡 -->
          <el-col :sm="9">
            <div class="right-content">
              <div class="datika">答题卡</div>
              <div class="tip">
                <div style="display: flex"><span class="yizuo"></span>已做</div>
                <div style="display: flex"><span class="wei"></span>未做</div>
              </div>
              <div class="option">
                <div class="qus-type" v-if="$route.query.row == 0">单选题</div>
                <div class="medium" v-if="$route.query.row == 0">
                  <div
                    v-for="(item, index) in danxuanList"
                    :key="item.id"
                    @click="
                      handleCheckQusetion(index, item, danxuanList, '单选题')
                    "
                  >
                    <div
                      class="op-box op-box-blue"
                      v-if="answerList[item.id] || item.option"
                      :style="
                        isSelect == item.id ? 'border:1px solid blue' : ''
                      "
                    >
                      {{ index + 1 }}
                    </div>
                    <div
                      v-else
                      class="op-box"
                      :style="
                        isSelect == item.id ? 'border:1px solid blue' : ''
                      "
                    >
                      {{ index + 1 }}
                    </div>
                  </div>
                </div>
                <div class="qus-type" v-if="$route.query.row == 1">多选题</div>
                <div class="medium" v-if="$route.query.row == 1">
                  <div
                    v-for="(item, index) in duoxuanList"
                    :key="item.id"
                    @click.prevent="
                      handleCheckQusetion(index, item, duoxuanList, '多选题')
                    "
                  >
                    <div
                      class="op-box op-box-blue"
                      v-if="answerList[item.id]"
                      :style="
                        isSelect == item.id ? 'border:1px solid blue' : ''
                      "
                    >
                      {{ index + 1 + danxuanList.length }}
                    </div>
                    <div
                      v-else
                      class="op-box"
                      :style="
                        isSelect == item.id ? 'border:1px solid blue' : ''
                      "
                    >
                      {{ index + 1 + danxuanList.length }}
                    </div>
                  </div>
                </div>
                <div class="qus-type" v-if="$route.query.row == 2">判断题</div>
                <div class="medium" v-if="$route.query.row == 2">
                  <div
                    v-for="(item, index) in panduanList"
                    :key="item.id"
                    @click.prevent="
                      handleCheckQusetion(index, item, panduanList, '判断题')
                    "
                  >
                    <div
                      class="op-box op-box-blue"
                      v-if="answerList[item.id] || item.option"
                      :style="
                        isSelect == item.id ? 'border:1px solid blue' : ''
                      "
                    >
                      {{ index + 1 + danxuanList.length + duoxuanList.length }}
                    </div>
                    <div
                      v-else
                      class="op-box"
                      :style="
                        isSelect == item.id ? 'border:1px solid blue' : ''
                      "
                    >
                      {{ index + 1 + danxuanList.length + duoxuanList.length }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- footer页脚 -->
    <!-- <m-fotter /> -->
  </div>
</template>

<script>
import { STATUS_CODE_OK } from "@/config";
import {
  getErrorBookPractice,
  getErrorBookPracticeSubmit,
} from "@/api/personalCenter";
// import MHeader from "@/components/MHeader.vue";
// import MFotter from "@/components/MFotter.vue";
export default {
  name: "again",
  data() {
    return {
      checkoptionlist: {},
      checkList: [],
      sujectType: "", // 题目类型
      mubiaoArray: [], //过渡数组-逻辑
      isOptuionSelcet: "", // 是否作答
      isSelect: "", // 是否点击答题卡
      timuList: {}, // 题目数据
      timuListCopy: {}, // 题目数据-副本
      answer: {}, // 答案提交数据
      answerList: {}, // 答案数据-本地
      questionNum: 1, // 题号
      questionNumcopy: 0, // 题号-副本
      panduanList: [], // 判断题
      duoxuanList: [], // 多选题
      danxuanList: [], // 单选题
      datalist: {}, // 路由数据-考试信息
      timer: null, // 计时器
      countDownTime: 3600, // 倒计时时间
      isSelfSub: false,
      zuotiList: {},
      submitState: 0, //提交状态
      isSubmitTrue: false,
    };
  },
  async created() {
    await this.handleGetContinueExam();
  },
  mounted() {
    document.addEventListener("contextmenu", this.preventContextMenu);
    document.onkeydown = function (e) {
      if (e.key === "F5" || e.keyCode == 116) {
        // F12, Ctrl+Shift+I, Ctrl+U
        // alert("功能已被禁用！");
        e.preventDefault();
        return false;
      }
    };
    window.addEventListener("beforeunload", this.onBeforeUnload);
  },
  beforeDestroy() {
    let isEmpty = false;
    window.removeEventListener("beforeunload", this.onBeforeUnload);
    let arr = localStorage.getItem(
      `ctanswerList${this.$store.state.userData.id}`
    );
    if (!this.isSubmitTrue) {
      for (let key in arr) {
        if (arr[key] !== "") {
          isEmpty = true;
          break;
        }
      }
      if (isEmpty) {
        this.handleSubmitPaper(); // 当所有属性值都为空字符串时提交
      }
    }

    localStorage.removeItem(`ctanswerList${this.$store.state.userData.id}`);
  },

  methods: {
    // 只切割第一个字符串
    splitFirst(str, delimiter) {
      const index = str.indexOf(delimiter);
      if (index === -1) {
        return [str]; // 如果没有找到分隔符，则返回原字符串
      }
      return [str.slice(0, index), str.slice(index + delimiter.length)];
    },
    onBeforeUnload(event) {
      const message = "您有未保存的更改，确定要离开吗？";
      event.returnValue = message; // 兼容性设置
      return message; // 兼容性设置
    },

    // 多选题选择
    handleCheckedChange(value, item) {
      if (value) {
        this.checkoptionlist[this.timuList.id] += item.split("、")[0];
        this.answerList[this.timuList.id] = this.checkoptionlist[
          this.timuList.id
        ]
          .split("undefined")[1]
          .split("")
          .sort()
          .join("");
      } else {
        let obj = JSON.parse(
          localStorage.getItem(`ctanswerList${this.$store.state.userData.id}`)
        );
        for (let key in obj) {
          if (key == this.timuList.id) {
            this.checkoptionlist[this.timuList.id] = "undefined" + obj[key];
            break;
          }
        }
        if (this.checkoptionlist[this.timuList.id]) {
          this.checkoptionlist[this.timuList.id] = this.checkoptionlist[
            this.timuList.id
          ].replace(item.split("、")[0], "");
          this.answerList[this.timuList.id] = this.checkoptionlist[
            this.timuList.id
          ]
            .split("undefined")[1]
            .split("")
            .sort()
            .join("");
        }
      }
      localStorage.setItem(
        `ctanswerList${this.$store.state.userData.id}`,
        JSON.stringify(this.answerList)
      );
    },
    async handleIsSubmit(isPush, isSubmit) {
      this.submitState = isSubmit;
      let isEmpty = false;
      let obj = JSON.parse(
        localStorage.getItem(`ctanswerList${this.$store.state.userData.id}`)
      );
      try {
        let msg = "确认交卷？";
        await this.$confirm(msg, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        if (!this.isSubmitTrue) {
          for (let key in obj) {
            if (obj[key] !== "") {
              isEmpty = true;
              break;
            }
          }
          if (isEmpty) {
            this.handleSubmitPaper(); // 当所有属性值都为空字符串时提交
          } else {
            this.$router.push("/wrongquestionrecord");
          }
        }
      } catch {
        console.log("取消");
      }
    },
    // 交卷 level: 1初 2中 3高
    async handleSubmitPaper() {
      this.answer = JSON.parse(
        localStorage.getItem(`ctanswerList${this.$store.state.userData.id}`)
      );
      let dataArrList = [];
      for (let key in this.answer) {
        dataArrList.push({
          id: key,
          value: this.answer[key],
        });
      }
      let noAnswerList = [];
      if (this.danxuanList.length > 0) {
        this.danxuanList.forEach((item) => {
          noAnswerList.push(item);
        });
      }
      if (this.duoxuanList.length > 0) {
        this.duoxuanList.forEach((item) => {
          noAnswerList.push(item);
        });
      }
      if (this.panduanList.length > 0) {
        this.panduanList.forEach((item) => {
          noAnswerList.push(item);
        });
      }
      const arrlist = noAnswerList.filter((item) => {
        return !dataArrList.some((eitem) => item.id === eitem.id);
      });
      let result = [];
      arrlist.forEach((item) => {
        result.push({
          id: item.id,
          value: null,
        });
      });
      let { data } = await getErrorBookPracticeSubmit({
        answerString: JSON.stringify(dataArrList),
        undoString: JSON.stringify(result),
      });
      if (data.code == STATUS_CODE_OK) {
        this.isSubmitTrue = true;
        const loading = this.$loading({
          text: "交卷中，请稍等~",
          lock: true,
          background: "rgba(0, 0, 0, 0.7)",
        });
        setTimeout(() => {
          loading.close();
          this.$router.push("/wrongquestionrecord");
        }, 2000);
      }
    },
    // 答题选项
    handleOptionTrue(item) {
      this.isOptuionSelcet = JSON.parse(JSON.stringify(item));
      this.answerList[this.timuList.id] = JSON.parse(
        JSON.stringify(item)
      ).split("、")[0];
      localStorage.setItem(
        `ctanswerList${this.$store.state.userData.id}`,
        JSON.stringify(this.answerList)
      );
    },
    // 答题卡选项
    handleCheckQusetion(index, item = {}, arr = [], type) {
      // index题号 item单题 arr题目集合 type题目类型
      if (arr.length < 1) {
        return false;
      }
      this.sujectType = type;
      this.questionNumcopy = index;
      if (this.sujectType == "多选题") {
        this.checkList = [];
        this.questionNumcopy = index + this.danxuanList.length;
        if (
          localStorage.getItem(`ctanswerList${this.$store.state.userData.id}`)
        ) {
          this.answerList = JSON.parse(
            localStorage.getItem(`ctanswerList${this.$store.state.userData.id}`)
          );
          for (let key in this.answerList) {
            if (key == item.id) {
              this.answerList[key].split("").forEach((item) => {
                this.checkList.push(item);
              });
            }
          }
        }
      }
      if (this.sujectType == "判断题") {
        this.questionNumcopy =
          index + this.danxuanList.length + this.duoxuanList.length;
      }
      if (arr.length >= 1) {
        this.mubiaoArray = arr;
      }
      this.isOptuionSelcet = this.answerList[item.id];
      this.questionNum = index;
      this.timuList = item;
      this.isSelect = item.id;
      if (typeof this.timuList.options != "object") {
        this.timuList.options = this.timuList.options.split(";;");
      }
      this.timuListCopy = JSON.parse(JSON.stringify(item));
      this.timuListCopy.options.forEach((item, eindex) => {
        this.timuListCopy.options.splice(eindex, 1, item.split("、")[0]);
      });
    },

    // 上一题下一题
    async handleNextQuestion(type) {
      let arr = [];
      if (this.sujectType == "单选题") {
        arr = this.danxuanList;
      }
      if (this.sujectType == "多选题") {
        arr = this.duoxuanList;
      }
      if (this.sujectType == "判断题") {
        arr = this.panduanList;
      }
      if (type == "last") {
        if (this.questionNum < 1 && this.sujectType == "单选题") {
          this.questionNum = 1;
          return;
        }
        if (this.questionNum == 0 && this.sujectType == "多选题") {
          if (this.danxuanList.length < 1) {
            return;
          }
          this.sujectType = "单选题";
          this.questionNum = this.danxuanList.length - 1;
          this.handleCheckQusetion(
            this.questionNum,
            this.danxuanList[this.questionNum],
            this.danxuanList,
            this.sujectType
          );
          return;
        } else if (this.questionNum == 0 && this.sujectType == "判断题") {
          if (this.duoxuanList.length < 1) {
            return;
          }
          this.sujectType = "多选题";
          this.questionNum = this.duoxuanList.length - 1;
          this.handleCheckQusetion(
            this.questionNum,
            this.duoxuanList[this.questionNum],
            this.duoxuanList,
            this.sujectType
          );
        } else {
          this.questionNum -= 1;
          this.handleCheckQusetion(
            this.questionNum,
            this.mubiaoArray[this.questionNum],
            arr,
            this.sujectType
          );
        }
      }
      if (type == "next") {
        if (
          this.questionNum > this.mubiaoArray.length - 2 &&
          this.sujectType == "判断题"
        ) {
          return;
        } else if (
          this.sujectType == "单选题" &&
          this.questionNum == this.mubiaoArray.length - 1
        ) {
          if (this.duoxuanList.length < 1) {
            return false;
          }
          this.sujectType = "多选题";
          this.questionNum = 0;
          this.handleCheckQusetion(
            this.questionNum,
            this.duoxuanList[this.questionNum],
            this.duoxuanList,
            this.sujectType
          );
          return;
        } else if (
          this.sujectType == "多选题" &&
          this.questionNum == this.mubiaoArray.length - 1
        ) {
          if (this.panduanList.length < 1) {
            return false;
          }
          this.sujectType = "判断题";
          this.questionNum = 0;
          this.handleCheckQusetion(
            this.questionNum,
            this.panduanList[this.questionNum],
            this.panduanList,
            this.sujectType
          );
        } else {
          this.questionNum += 1;
          this.handleCheckQusetion(
            this.questionNum,
            this.mubiaoArray[this.questionNum],
            arr,
            this.sujectType
          );
        }
      }
    },
    // 退出
    async goBack() {
      let tisEmpty = false;
      let arr = localStorage.getItem(
        `ctanswerList${this.$store.state.userData.id}`
      );
      this.submitState = 0;
      let msg = "退出视为交卷，是否退出练习?";
      try {
        await this.$confirm(msg, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        for (let key in arr) {
          if (arr[key] !== "") {
            tisEmpty = true;
            break;
          }
        }
        if (tisEmpty) {
          this.handleSubmitPaper(); // 当所有属性值都为空字符串时提交
        } else {
          this.$router.push("/wrongquestionrecord");
        }
      } catch {
        console.log("取消");
      }
    },

    //
    async handleGetContinueExam() {
      let { data } = await getErrorBookPractice({
        topicType: this.$route.query.row,
      });
      if (data.code == STATUS_CODE_OK) {
        this.zuotiList = data.data;
        this.panduanList = data.data.judge;
        this.duoxuanList = data.data.multiple;
        this.danxuanList = data.data.single;
        this.danxuanList.forEach((item) => {
          item.isselect = false;
        });
        this.panduanList.forEach((item) => {
          if (item.option) {
            this.answerList[item.id] = item.option;
          }
        });
        this.duoxuanList.forEach((item) => {
          if (item.option) {
            this.answerList[item.id] = item.option;
          }
        });
        this.danxuanList.forEach((item) => {
          if (item.option) {
            this.answerList[item.id] = item.option;
          }
        });
        if (this.duoxuanList.length > 0) {
          this.handleCheckQusetion(
            0,
            this.duoxuanList[0],
            this.duoxuanList,
            "多选题"
          );
        }
        if (this.danxuanList.length > 0) {
          this.handleCheckQusetion(
            0,
            this.danxuanList[0],
            this.danxuanList,
            "单选题"
          );
        }
        if (this.panduanList.length > 0) {
          this.handleCheckQusetion(
            0,
            this.panduanList[0],
            this.panduanList,
            "判断题"
          );
        }
      }
    },
  },
  // components: {
  //   MHeader,
  //   MFotter,
  // },
};
</script>
<style lang="scss" scoped>
.el-page-header {
  background: #fff;
  padding: 10px;
}
::v-deep .el-row {
  width: 100%;
  max-width: 1200px;
}
::v-deep .el-page-header__title {
  line-height: 23px !important;
  width: 60px !important;
  text-align: center;
  height: 26px !important;
  color: #ff9500;
  margin-top: 8px;
  /* line-height: 43px; */
  border-radius: 20px;
  border: 1px solid #ff9500;
}
::v-deep .el-page-header__left .el-icon-back {
  display: none;
}
::v-deep .is-option-select {
  background: #1968fa !important;
}
::v-deep .el-checkbox__input.is-checked .el-checkbox__inner,
.el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background: #1968fa !important;
}
::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #1968fa !important;
}
::v-deep .el-checkbox__label {
  color: #000;
}
::v-deep .el-checkbox-button {
  position: relative;
  margin: 0px 10px !important;
}
::v-deep .el-checkbox-button__inner {
  border: 1px solid #8d9399;
  color: #8d9399 !important;
  text-align: none !important;
  box-sizing: border-box !important;
  margin: 0px !important;
  transition: none !important;
  padding: 0px !important;
  border-radius: none !important;
  display: flex !important;
  justify-content: space-evenly !important;
  align-items: center !important;
  width: 30px !important;
  height: 30px !important;
  cursor: pointer !important;
  font-size: 14px !important;
  border-radius: 0 !important;
}
::v-deep .el-page-header__title {
  width: 30px;
  line-height: 43px;
}
::v-deep .el-page-header__left {
  margin-right: -44px;
}

::v-deep .el-page-header__content {
  font-size: 22px;
  color: #333;
  text-align: center;
  // width: 1200px;
  margin: 0px auto;
  line-height: 43px;
}
.time-down {
  width: 1200px;
  color: #fff;
  font-weight: bold;
  font-size: 26px;
  background: url("../../assets/images/timeback.png");
  margin: 10px auto;
  padding: 20px;
  text-align: center;
}
.subject {
  .submit {
    background: #fff;
    padding: 20px 0px;
    display: flex;
    justify-content: space-evenly;
    margin-bottom: 20px;
    .el-button {
      width: 300px;
    }
  }
  .nextlast-box {
    margin: 20px 0px;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    height: 72px;
    background: #fff;
    .btn-box {
      .el-button {
        border: 1px solid #409eff;
        color: #409eff;
      }
      .last-btn {
        width: 160px;
        margin: 0px 30px;
      }
      .next-btn {
        width: 160px;
        margin: 0px 30px;
      }
    }
  }
  background: #eee;
  .left-content {
    background: #fff;
  }
  .right-content {
    min-height: 620px;
    padding: 15px 0px;
    .tip {
      display: flex;
      justify-content: space-evenly;
      margin-bottom: 20px;
      .yizuo {
        background: #1968fa;
        width: 20px;
        height: 20px;
        border-radius: 2px;
        display: inline-block;
        margin-right: 10px;
      }
      .wei {
        margin-right: 10px;
        background: #fff;
        width: 20px;
        height: 20px;
        border-radius: 2px;
        display: inline-block;
        border: 1px solid #8d9399;
      }
    }
    .datika {
      font-size: 18px;
      color: #333;
      font-weight: bold;
      padding: 20px 0px;
      margin: 0px 30px;
      margin-bottom: 20px;
      border-bottom: 1px solid #eee;
      box-sizing: border-box;
    }
    background: #fff;
    margin-top: 10px;
    .option {
      margin: 0px 30px;
      .medium {
        display: flex;
        flex-wrap: wrap;
        max-height: 444px;
        overflow-y: auto;
        .op-active {
          border: 1px solid #1968fa;
          color: #fff !important;
        }
        .op-box-blue {
          background: #1968fa;
          color: #fff !important;
        }
        .op-box {
          color: #8d9399;
          cursor: pointer;
          width: 30px;
          height: 30px;
          border: 1px solid #8d9399;
          margin: 10px;
          text-align: center;
          line-height: 30px;
        }
      }
      .qus-type {
        font-size: 14px;
        font-weight: bold;
        margin-top: 20px;
      }
    }
  }
}
/*el-scrollbar 必须指定高度*/
.scrollMenuBox {
  height: 344px;
  padding: 10px 23px 0px;
  .subbox-box {
    font-size: 16px;
    margin: 10px;
    .subbox {
      margin-top: 20px;
      margin-left: 60px;
      .check-options {
        padding: 10px 0px;
        font-size: 14px;
        display: flex;
        flex-direction: column;
      }
      .options {
        padding: 10px 0px;
        font-size: 14px;
        display: flex;
        align-items: center;
        .is-option-select {
          background: #409eff;
          color: #fff;
          border: 1px solid #fff !important;
        }
        .is-checkbox-select {
          background: #409eff;
          color: #fff;
          border: 1px solid #fff !important;
        }
        .check-option {
          width: 25px;
          height: 25px;
          display: inline-block;
          border: 1px solid #73797f;
          text-align: center;
          line-height: 18px;
          font-size: 12px;
          margin-right: 10px;
        }
        .option {
          width: 25px;
          height: 25px;
          display: inline-block;
          border: 1px solid #73797f;
          text-align: center;
          line-height: 23px;
          border-radius: 100px;
          font-size: 12px;
          margin-right: 10px;
        }
      }
    }
  }
}
.tihao {
  display: inline-block;
  width: 19px;
  height: 30px;
  text-align: center;
  line-height: 25px;
  color: #fff;
  font-size: 12px;
  background: url("../../assets/images/tihao.png") 100% no-repeat;
}
</style>
